package com.iw.point.dao;

import com.iw.adoms.dao.GoodsDao;
import com.iw.adoms.dao.QrGoodsCodeDao;
import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.QrGoodsCode;
import com.iw.point.entity.PointType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.iw.core.orm.hibernate.BaseDao;
import com.iw.point.entity.PointRecord;

import java.util.List;

@Repository
public class PointRecordDao extends BaseDao<PointRecord> {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private QrGoodsCodeDao qrGoodsCodeDao;

    @Override
    public void save(PointRecord entity) {

        //select g.* from goods g,qr_goods_code q where g.qr_code_id = q.id and q.i_code = '108409251206' order by g.insert_time desc ;

        String iCode = entity.getiCode();
        if (StringUtils.isNotBlank(iCode)) {
            String hql = "from QrGoodsCode q where  q.iCode = ? and 1=?";
            QrGoodsCode qr = qrGoodsCodeDao.find("iCode", iCode);
            if (qr != null) {
                hql = "from Goods g where g.qrCode.id = ? and 1=? order by g.insertTime desc";
                List<Goods> gList = goodsDao.findList(hql, qr.getId(), 1);
                if (gList != null && !gList.isEmpty()) {
                    entity.setIdepart(gList.get(0).getDepartment());
                }
            }
        }

        super.save(entity);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public void update(PointRecord entity) {
        String iCode = entity.getiCode();
        if (StringUtils.isNotBlank(iCode)) {
            if (entity.getType().equals(PointType.CONVERT_TEL)) {

            } else {
                String hql = "from QrGoodsCode q where  q.iCode = ? and 1=?";
                QrGoodsCode qr = qrGoodsCodeDao.find("iCode", iCode);
                if (qr != null) {
                    hql = "from Goods g where g.qrCode.id = ? and 1=? order by g.insertTime desc";
                    List<Goods> gList = goodsDao.findList(hql, qr.getId(), 1);
                    if (gList != null && !gList.isEmpty()) {
                        entity.setIdepart(gList.get(0).getDepartment());
                    }
                }
            }

        }
        super.update(entity);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
